package com.sne.airways.customer.dao.impl;

import com.sne.airways.basecore.dao.impl.BaseDAOHibernate;
import com.sne.airways.customer.dao.CustDAO;
import com.sne.airways.customer.pojo.TdCust;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-12-22
 * Time: 下午5:26
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class CustDAOHibernate extends BaseDAOHibernate implements CustDAO {
    @Override
    public List<TdCust> queryCustList(int start, int limit, String custName, String custPhone,String custType) {
        Session session = getSession();
        StringBuffer sb = new StringBuffer();
        sb.append(" from TdCust tc where 1=1");
        if ( StringUtils.isNotBlank ( custName ) ) {
            sb.append(" and tc.custName like :custName ");
        }
        if ( StringUtils.isNotBlank ( custPhone ) ) {
            sb.append(" and tc.phone like :custPhone ");
        }
        if ( StringUtils.isNotBlank ( custType ) ) {
            sb.append(" and tc.custType like :custType ");
        }
        Query query = session.createQuery(sb.toString());
        if ( StringUtils.isNotBlank ( custName ) ) {
            query.setString("custName","%"+custName+"%");
        }
        if ( StringUtils.isNotBlank ( custPhone ) ) {
            query.setString("custPhone","%"+custPhone+"%");
        }
        if ( StringUtils.isNotBlank ( custType ) ) {
            query.setString("custType","%"+custType+"%");
        }
        return query.setFirstResult(start).setMaxResults(limit).list();
    }

    @Override
    public Integer queryCustCount(String custName, String custPhone,String custType) {
        Session session = getSession();
        StringBuffer sb = new StringBuffer();
        sb.append(" select count(*) from TdCust tc where 1=1");
        if ( StringUtils.isNotBlank ( custName ) ) {
            sb.append(" and tc.custName like :custName ");
        }
        if ( StringUtils.isNotBlank ( custPhone ) ) {
            sb.append(" and tc.phone like :custPhone ");
        }
        if ( StringUtils.isNotBlank ( custType ) ) {
            sb.append(" and tc.custType like :custType ");
        }
        Query query = session.createQuery(sb.toString());
        if ( StringUtils.isNotBlank ( custName ) ) {
            query.setString("custName","%"+custName+"%");
        }
        if ( StringUtils.isNotBlank ( custPhone ) ) {
            query.setString("custPhone","%"+custPhone+"%");
        }
        if ( StringUtils.isNotBlank ( custType ) ) {
            query.setString("custType","%"+custType+"%");
        }
        return ((Long)query.uniqueResult()).intValue();
    }
}
